//
//  AwemeListController.m
//  Douyin
//
//  Created by Qiao Shi on 2018/7/30.
//  Copyright © 2018年 Qiao Shi. All rights reserved.
//

#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "AwemeListController.h"
#import "AwemeListCell.h"
//#import "NetworkHelper.h"
#import "LoadMoreControl.h"
#import "AVPlayerManager.h"
#import "MHAwemeListViewModel.h"
#import "MHMomentViewModel.h"
#import "MHDetailLocationViewModel.h"
#define AWEME_CELL @"AwemeListCell"
#import "MHRedPacketRecordViewModel.h"
#import "MHRedPacketRecevieModel.h"
#import "SharePopView.h"
@interface AwemeListController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, assign) BOOL                              isCurPlayerPause;
@property (nonatomic, assign) NSInteger                         pageIndex;
@property (nonatomic, assign) NSInteger                         pageSize;
@property (nonatomic, assign) AwemeType                         awemeType;
@property (nonatomic, copy) NSString                            *uid;

@property (nonatomic, strong) NSMutableArray<MHAwemeModel *>           *data;
@property (nonatomic, strong) NSMutableArray<MHAwemeModel *>           *awemes;
@property (nonatomic, strong) LoadMoreControl                      *loadMore;

@property(nonatomic, strong) MHAwemeListViewModel *viewModel;

@end
@implementation AwemeListController
@dynamic viewModel;
-(instancetype)initWithVideoData:(NSMutableArray<MHAwemeModel *> *)data currentIndex:(NSInteger)currentIndex pageIndex:(NSInteger)pageIndex pageSize:(NSInteger)pageSize awemeType:(AwemeType)type uid:(NSString *)uid {
    self = [super init];
    if(self) {
        _isCurPlayerPause = NO;
        _currentIndex = currentIndex;
        _pageIndex = pageIndex;
        _pageSize = pageSize;
        _awemeType = type;
        _uid = uid;
        
        _awemes = [data mutableCopy];
        _data = [[NSMutableArray alloc] initWithObjects:[_awemes objectAtIndex:_currentIndex], nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//     self.fd_prefersNavigationBarHidden = YES;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self applicationBecomeActive];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBackgroundImage:@"img_video_loading"];
    [self setUpView];
//    [self set]
    [self setLeftButton:@"icon_titlebar_whiteback"];
    @weakify(self);
    [[MHNotificationCenter rac_addObserverForName:MHRedPacketReceviceNotification object:nil] subscribeNext:^(NSNotification *note) {
        @strongify(self);
         MHRedPacketRecevieModel *model  =  note.object;
        AwemeListCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
        if(model.recentId == cell.aweme.recentId)
        {
           cell.redPacketLeftLabel.text = [NSString stringWithFormat:@"剩余%d个",model.surplusNum];
        }

    }];
    
}


-(void) dismiss
{
    [_tableView.layer removeAllAnimations];
    NSArray<AwemeListCell *> *cells = [_tableView visibleCells];
    for(AwemeListCell *cell in cells) {
        [cell.playerView cancelLoading];
        
    }
    

    [self.viewModel.services popViewModelAnimated:YES];
}

-(void)bindViewModel
{
    [super bindViewModel];
    _isCurPlayerPause = NO;
    _currentIndex = 0;
    
    _pageSize = 8;
    //    _awemeType = type;
    //    _uid = uid;
    
    _awemes = [self.viewModel.awemeModels mutableCopy];
    _pageIndex = _awemes.count > 0 ? 1 : 0;
//    _pageIndex = self.viewModel.awemeModels.count > 0 ;
    _data = [[NSMutableArray alloc] initWithObjects:[_awemes objectAtIndex:_currentIndex], nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
}




-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"currentIndex"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void) setBackgroundImage:(NSString *)imageName {
    UIImageView *background = [[UIImageView alloc] initWithFrame:self.view.bounds];
    background.clipsToBounds = YES;
    background.contentMode = UIViewContentModeScaleAspectFill;
    background.image = [UIImage imageNamed:imageName];
    [self.view addSubview:background];
}

- (void)setUpView {
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    _tableView.backgroundColor = ColorClear;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.tableView registerClass:AwemeListCell.class forCellReuseIdentifier:AWEME_CELL];
    
    _loadMore = [[LoadMoreControl alloc] initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, 50) surplusCount:10];
    __weak __typeof(self) wself = self;
    if (!self.viewModel.showSingleVideo) {
        [_loadMore setOnLoad:^{
            [wself loadData:wself.pageIndex pageSize:wself.pageSize];
        }];
        [_tableView addSubview:_loadMore];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [wself.view addSubview:wself.tableView];
        wself.data = wself.awemes;
        [wself.tableView reloadData];
        if (wself.awemes.count > 0) {
            NSIndexPath *curIndexPath = [NSIndexPath indexPathForRow:wself.currentIndex inSection:0];
            [wself.tableView scrollToRowAtIndexPath:curIndexPath atScrollPosition:UITableViewScrollPositionMiddle
                                          animated:NO];
        }else
        {
            [wself loadData:wself.pageSize pageSize:wself.pageSize];
        }
        
       
        [wself addObserver:wself forKeyPath:@"currentIndex" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
        
    });
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
//    self.navigationController.navigationBar.translucent = NO;
}
-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self applicationEnterBackground];
//    self.fd_prefersNavigationBarHidden = false;
    
//    [_tableView.layer removeAllAnimations];
    
//    NSArray<AwemeListCell *> *cells = [_tableView visibleCells];
//    for(AwemeListCell *cell in cells) {
//        [cell.playerView pause];
//    }
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    [self removeObserver:self forKeyPath:@"currentIndex"];
//
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
}

#pragma tableView delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.view.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //填充视频数据
    AwemeListCell *cell = [tableView dequeueReusableCellWithIdentifier:AWEME_CELL];

    MHAwemeModel *model =   [_data objectAtIndex:indexPath.row];
    cell.location = self.viewModel.location;
    [cell initData:model];
    cell.avatar.userInteractionEnabled = YES;
    cell.avatar.tag = indexPath.row;
    __weak __typeof(self)weakSelf = self;
    
    [cell.redPacketBtn bk_whenTapped:^{
        MHAwemeModel *blockModel =   [weakSelf.data objectAtIndex:cell.avatar.tag];
        if (blockModel.redInfo.type == RedPacketShare && blockModel.redInfo.status == RedPacketGoing && !blockModel.redInfo.isHaveReceived) {
             [weakSelf showPopView];
        }else
        {
            MHRedPacketRecordViewModel *record = [[MHRedPacketRecordViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelIDKey:@(blockModel.redInfo.autoId)}];
            [weakSelf.viewModel.services pushViewModel:record animated:YES];
        }
       
    }];
    
    [cell.avatar bk_whenTapped:^{
        MHAwemeModel *blockModel =   [weakSelf.data objectAtIndex:cell.avatar.tag];
        IMAUser *user = [[IMAUser alloc] initWith:[NSString stringWithFormat:@"%d",blockModel.publishUserId]];
        user.icon = blockModel.allPublishUserHeadPic;
        user.nickName = blockModel.publishUserName;
        IMAConversation *conversation =  [[IMAPlatform sharedInstance].conversationMgr chatWith:user];
        MHMomentViewModel *viewModel = [[MHMomentViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelIsFootPrint:@(true),MHViewModelTitleKey:isEquaalCurrentUserId(user.userId)?@"我的足迹":@"Ta的足迹",MHViewModelConversation:conversation}];
        viewModel.userId = [user.userId intValue];
        viewModel.imUser = user;
        [weakSelf.viewModel.services pushViewModel:viewModel animated:YES];
    }];
    //    cell.enterBtn.hidden = !self.viewModel.showEnterBtn;
    if (!self.viewModel.showEnterBtn) {
        [cell.enterBtn setTitle:@"进入圈子" forState:0];
    }
    cell.enterBtn.hidden = self.viewModel.hiddenEnter;
//    __weak __typeof(self)weakSelf = self;
    [cell.locationBtn bk_whenTapped:^{
//        CLLocation *location = [[CLLocation alloc] initWithLatitude:model.location.lat longitude:model.location.lon];
        MHDetailLocationViewModel *locationViewModel =  [[MHDetailLocationViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelUtilKey:model.location }];
        [weakSelf.viewModel.services pushViewModel:locationViewModel  animated: YES];
    }];
    cell.enterBtn.tag = indexPath.row;
    [cell.enterBtn addTarget:self action:@selector(enterOrJionCircle:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

-(void) enterOrJionCircle:(UIButton *) btn
{
    MHDiscoverHomeModel *model = [MHDiscoverHomeModel new];
    MHAwemeModel *aweme =  [_data objectAtIndex:btn.tag];
    model.circleId = aweme.circleId;
    model.isInCircle = aweme.isInCircle;
    model.circleName = aweme.circleName;
    model.circleCode = aweme.circleCode;
    model.payType = aweme.payType;
    [AXAppDelegate sharedDelegate].currentDiscoverModel = model;
    
    @weakify(self);
    [MHMomentHelper enterOrJionCircleWithViewModel:self.viewModel joinSuccessBlock:^{
        @strongify(self);
//        [AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle = YES;
        aweme.isInCircle = YES;
        [btn setTitle:@"进入圈子" forState:0];
    }];
}

-(void) showPopView
{
    
    MHAwemeModel *_awemeModel = self.data[self.currentIndex];
    SharePopView *popView;
    if (_awemeModel.redInfo.type == RedPacketShare) {
        popView =  [[SharePopView alloc] initWithNameArr:@[@"朋友圈"] iconsNames:@[@"ic_share_pyq"] containerHeight:190 itemHeight:100 showHeader:YES headerText:@"微信红包分享到朋友圈可以领红包"];
    }else
    {
        popView =  [[SharePopView alloc] initWithNameArr:@[@"微信",@"朋友圈"] iconsNames:@[@"ic_share_wx",@"ic_share_pyq"] containerHeight:190 itemHeight:100 showHeader:YES headerText:@"微信红包分享到微信或朋友圈可以领红包"];
    }
    __weak __typeof(self)weakSelf = self;
    __weak __typeof(popView) weakPopView = popView;
    popView.circleBottonCilckBlock = ^(int index) {
        [weakPopView dismiss];
        
        switch (index) {
                
            case 0:
            {
                
                [[[[MHHTTPService sharedInstance] shareRecentStoryWithCircleId:_awemeModel.circleId recentId:_awemeModel.recentId] mh_parsedResults] subscribeNext:^(MHshareRecent *share) {
                    
                    [MHMomentHelper shareWithSharRecent:share shareType:MHCirclShareTypeWeChat];
                }];
                
            }
                break;
            case 1:
            {
                [[[[MHHTTPService sharedInstance] shareRecentStoryWithCircleId:_awemeModel.circleId recentId:_awemeModel.recentId] mh_parsedResults] subscribeNext:^(MHshareRecent *share) {
                    [MHMomentHelper shareWithSharRecent:share shareType:MHCirclShareTypeWeChatTimeLine];
                }];
            }
                
                break;
            default:
                break;
        }
    };
    [popView show];
}
//-(void)dealloc
//{
//  
//    NSLog(@"cccc");
////    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:nil];
////    [self removeObserver:self forKeyPath:@"currentIndex"];
////    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}


#pragma ScrollView delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    dispatch_async(dispatch_get_main_queue(), ^{
        CGPoint translatedPoint = [scrollView.panGestureRecognizer translationInView:scrollView];
        //UITableView禁止响应其他滑动手势
        scrollView.panGestureRecognizer.enabled = NO;
        
        if (self.data.count <= 0) {
            return ;
        }
        AwemeListCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
        [cell cancelTime];
        if(translatedPoint.y < -50 && self.currentIndex < (self.data.count - 1)) {
            self.currentIndex ++;   //向下滑动索引递增
        }
        if(translatedPoint.y > 50 && self.currentIndex > 0) {
            self.currentIndex --;   //向上滑动索引递减
        }
        AwemeListCell *curretCell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
        MHAwemeModel *model =   [self.data objectAtIndex:self.currentIndex];
        
        if (model.redInfo.status == RedPacketGoing && !model.redInfo.isHaveReceived && model.redInfo.type != RedPacketShare) {
//            [curretCell redPacketCoutDown];
//             [curretCell configWithRedInfoWith:model];
        }else
        {
            [curretCell configWithRedInfoWith:model];
        }
        __weak __typeof(self)weakSelf = self;
        [UIView animateWithDuration:0.15
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut animations:^{
                                //UITableView滑动到指定cell
                                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.currentIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                            } completion:^(BOOL finished) {
                                //UITableView可以响应其他滑动手势
                                scrollView.panGestureRecognizer.enabled = YES;
                            }];
        
    });
}

#pragma KVO
- (void)applicationBecomeActive {
    AwemeListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    if(!_isCurPlayerPause) {
        [cell.playerView play];
    }
}

- (void)applicationEnterBackground {
    AwemeListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    _isCurPlayerPause = ![cell.playerView rate];
    [cell.playerView pause];
}

//观察currentIndex变化
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentIndex"]) {
        //设置用于标记当前视频是否播放的BOOL值为NO
        _isCurPlayerPause = NO;
        //获取当前显示的cell
        AwemeListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
        __weak typeof (cell) wcell = cell;
        __weak typeof (self) wself = self;
        //判断当前cell的视频源是否已经准备播放
        if(cell.isPlayerReady) {
            //播放视频
            [cell play];
            if (cell.aweme.redInfo.status == RedPacketGoing && !cell.aweme.redInfo.isHaveReceived && cell.aweme.redInfo.type != RedPacketShare) {
                [cell redPacketCoutDown];
            }
        }else {
            [[AVPlayerManager shareManager] pauseAll];
            //当前cell的视频源还未准备好播放，则实现cell的OnPlayerReady Block 用于等带视频准备好后通知播放
            cell.onPlayerReady = ^{
                NSIndexPath *indexPath = [wself.tableView indexPathForCell:wcell];
                if(!wself.isCurPlayerPause && indexPath && indexPath.row == wself.currentIndex) {
                    [wcell play];
                    if (wcell.aweme.redInfo.status == RedPacketGoing && !wcell.aweme.redInfo.isHaveReceived && wcell.aweme.redInfo.type != RedPacketShare) {
                        [wcell redPacketCoutDown];
                    }
                }else
                {
                }
            };
        }
    } else {
        return [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma load data
- (void)loadData:(NSInteger)pageIndex pageSize:(NSInteger)pageSize {
    @weakify(self);
    self.pageIndex++;
    
    if (self.viewModel.circleMoment) {
        
        //收藏
        if(self.viewModel.isCollectionList)
        {
            [[[self.viewModel.services.client getRecentVideoPagedListByUserCollectWithMarkId:self.viewModel.circleMoment.autoId pageNum:self.pageIndex pageSize:pageSize] mh_parsedResults] subscribeNext:^(NSArray *modeArr) {
                 @strongify(self);
                [self updateTableViewData:modeArr];
            }];
        }else
        {
            if (self.viewModel.isNearyBy) {
                [[[self.viewModel.services.client getRecentVideoPagedListByNearbyWithRecentId:self.viewModel.circleMoment.recentId locationLon:self.viewModel.location.coordinate.longitude locationLat:self.viewModel.location.coordinate.latitude pageNum:self.pageIndex pageSize:pageSize n:self.viewModel.order] mh_parsedResults] subscribeNext:^(NSArray *modeArr) {
                    @strongify(self);
                    [self updateTableViewData:modeArr];
                }];
            }else if(self.viewModel.isProfile)
            {
                [[[self.viewModel.services.client getVideoPagedListByMyRecentWithRecentId:self.viewModel.circleMoment.recentId PageNum:self.pageIndex pageSize:pageSize] mh_parsedResults] subscribeNext:^(NSArray *modeArr) {
                    @strongify(self);
                    [self updateTableViewData:modeArr];
                }];
            }
            else
            {
                //特殊处理
                if (self.viewModel.circleMoment && self.viewModel.circleMoment.circleId > 0) {
                    [[[self.viewModel.services.client getRecentPagedListByNewVideoTimeDescWithRecentId:self.viewModel.circleMoment.autoId circleId:self.viewModel.circleMoment.circleId pageNum:self.pageIndex pageSize:pageSize] mh_parsedResults]  subscribeNext:^(NSArray *modeArr) {
                        @strongify(self);
                        [self updateTableViewData:modeArr];
                    }];
                }else
                {
                    [[[self.viewModel.services.client getRecentPagedListByNewVideoTimeDescWithRecentId:self.viewModel.circleMoment.autoId circleId: self.viewModel.isTimeLineList ? 0 : [AXAppDelegate sharedDelegate].currentCircleInfo.autoId pageNum:self.pageIndex pageSize:pageSize] mh_parsedResults]  subscribeNext:^(NSArray *modeArr) {
                        @strongify(self);
                        [self updateTableViewData:modeArr];
                    }];
                }
              
            }
            
        }
        
    }else
    {
        
//        if()
        
        [[[self.viewModel.services.client getRecentListByNewVideoWithRecentId:nil pageNum:self.pageIndex pageSize:pageSize] mh_parsedResults] subscribeNext:^(NSArray *modeArr) {
            @strongify(self);
            [self updateTableViewData:modeArr];
        }];
        
        
        
    }
    
}

-(void) updateTableViewData:(NSArray *) modeArr
{
    
    if(modeArr.count > 0) {
        
        if (self.viewModel.circleMoment && self.pageIndex == 1) {
            MHAwemeModel *first =  [modeArr firstObject];
            if (first.autoId != self.viewModel.circleMoment.autoId && first.autoId != self.viewModel.circleMoment.recentId) {
                [UIWindow showTips:@"主题找不到或已被删除\n3秒后为您加载下一个视频"];
                __weak __typeof(self)weakSelf = self;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf updateWithAwemeArray:modeArr];
                });
            }else
            {
                 [self updateWithAwemeArray:modeArr];
            }
        }else
        {
            [self updateWithAwemeArray:modeArr];
        }
        
    }else {
        [self.loadMore loadingAll];
        if (self.pageIndex == 1) {
            [UIWindow showTips:@"主题找不到或已被删除"];
        }
        
    }
}

-(void) updateWithAwemeArray:(NSArray *) arr
{
    [self.tableView beginUpdates];
    [self.data addObjectsFromArray:arr];
    NSMutableArray<NSIndexPath *> *indexPaths = [NSMutableArray array];
    for(NSInteger row = self.data.count - arr.count; row<self.data.count; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [indexPaths addObject:indexPath];
    }
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:NO];
    
    [self.tableView endUpdates];
    if (self.pageIndex == 1) {
        self.currentIndex = 0;
    }
    [self.loadMore endLoading];
}

@end
